<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>登录与注册</title>
    <!-- 引入Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <!-- 配置Tailwind -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#2563eb',
                        success: '#10b981',
                        danger: '#ef4444',
                        neutral: {
                            100: '#f3f4f6',
                            200: '#e5e7eb',
                            300: '#d1d5db',
                            600: '#4b5563',
                            700: '#374151',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    }
                },
            }
        }
    </script>

    <!-- 自定义工具类 -->
    <style type="text/tailwindcss">
        @layer utilities {
            .form-focus {
                @apply focus:border-primary focus:ring-2 focus:ring-primary/20 focus:outline-none;
            }
            .btn-effect {
                @apply transition-all duration-300 hover:shadow-lg transform hover:-translate-y-0.5 active:translate-y-0;
            }
            .slide-enter {
                animation: slideIn 0.3s ease-out forwards;
            }
            .slide-exit {
                animation: slideOut 0.3s ease-in forwards;
            }
        }

        @keyframes slideIn {
            from { transform: translateX(20px); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        @keyframes slideOut {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(-20px); opacity: 0; }
        }
    </style>
</head>
<body class="font-inter bg-gradient-to-br from-blue-50 to-indigo-50 min-h-screen flex items-center justify-center p-4">
<!-- 主容器 -->
<div class="w-full max-w-md">
    <!-- 卡片容器 -->
    <div class="bg-white rounded-xl shadow-lg overflow-hidden">
        <!-- 标题区域 -->
        <div class="bg-primary/5 px-6 py-4 border-b border-primary/10">
            <h1 class="text-[clamp(1.5rem,3vw,1.8rem)] font-bold text-neutral-700 text-center">账户访问</h1>
        </div>

        <!-- 标签切换 -->
        <div class="flex border-b border-neutral-200">
            <button id="login-tab" class="flex-1 py-3 font-medium text-primary border-b-2 border-primary transition-all">
                登录
            </button>
            <button id="register-tab" class="flex-1 py-3 font-medium text-neutral-500 hover:text-neutral-700 transition-all">
                注册
            </button>
        </div>

        <!-- 表单容器 -->

        <div class="p-6 md:p-8">
            <!-- 登录表单 -->
            <form id="login-form" class="space-y-5">
                <!-- 用户名 -->
                <div class="space-y-2">
                    <label for="login-username" class="block text-sm font-medium text-neutral-700">
                        用户名
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-neutral-400">
                            <i class="fa fa-user"></i>
                        </div>
                        <input type="text" id="login-username"
                               class="w-full pl-10 pr-4 py-3 border border-neutral-200 rounded-lg form-focus transition-all"
                               placeholder="请输入用户名" required
                               minlength="3" maxlength="20">
                    </div>
                    <p class="login-username-error hidden text-danger text-sm">用户名长度需3-20个字符</p>
                </div>

                <!-- 密码 -->
                <div class="space-y-2">
                    <label for="login-password" class="block text-sm font-medium text-neutral-700">
                        密码
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-neutral-400">
                            <i class="fa fa-lock"></i>
                        </div>
                        <input type="password" id="login-password"
                               class="w-full pl-10 pr-10 py-3 border border-neutral-200 rounded-lg form-focus transition-all"
                               placeholder="请输入密码" required
                               minlength="6">
                        <button type="button" class="toggle-password absolute inset-y-0 right-0 pr-3 flex items-center text-neutral-400 hover:text-neutral-700 transition-colors" data-target="login-password">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                    <p class="login-password-error hidden text-danger text-sm">密码长度至少6个字符</p>
                </div>
                <!-- 登录表单内添加 -->
                <div id="login-error" class="text-danger hidden mb-2"></div>
                <!-- 登录按钮 -->
                <button type="submit" class="w-full bg-primary text-white font-medium py-3 px-4 rounded-lg btn-effect">
                    登录
                </button>
            </form>

            <!-- 注册表单 (默认隐藏) -->
            <form id="register-form" class="space-y-5 hidden">
                <!-- 用户名 -->
                <div class="space-y-2">
                    <label for="register-username" class="block text-sm font-medium text-neutral-700">
                        用户名
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-neutral-400">
                            <i class="fa fa-user-plus"></i>
                        </div>
                        <input type="text" id="register-username"
                               class="w-full pl-10 pr-4 py-3 border border-neutral-200 rounded-lg form-focus transition-all"
                               placeholder="设置用户名" required
                               minlength="3" maxlength="20">
                    </div>
                    <p class="register-username-error hidden text-danger text-sm">用户名长度需3-20个字符</p>
                </div>

                <!-- 密码 -->
                <div class="space-y-2">
                    <label for="register-password" class="block text-sm font-medium text-neutral-700">
                        密码
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-neutral-400">
                            <i class="fa fa-lock"></i>
                        </div>
                        <input type="password" id="register-password"
                               class="w-full pl-10 pr-10 py-3 border border-neutral-200 rounded-lg form-focus transition-all"
                               placeholder="设置密码" required
                               minlength="6">
                        <button type="button" class="toggle-password absolute inset-y-0 right-0 pr-3 flex items-center text-neutral-400 hover:text-neutral-700 transition-colors" data-target="register-password">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                    <p class="register-password-error hidden text-danger text-sm">密码长度至少6个字符</p>
                </div>

                <!-- 确认密码 -->
                <div class="space-y-2">
                    <label for="confirm-password" class="block text-sm font-medium text-neutral-700">
                        确认密码
                    </label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none text-neutral-400">
                            <i class="fa fa-lock"></i>
                        </div>
                        <input type="password" id="confirm-password"
                               class="w-full pl-10 pr-10 py-3 border border-neutral-200 rounded-lg form-focus transition-all"
                               placeholder="再次输入密码" required>
                        <button type="button" class="toggle-password absolute inset-y-0 right-0 pr-3 flex items-center text-neutral-400 hover:text-neutral-700 transition-colors" data-target="confirm-password">
                            <i class="fa fa-eye-slash"></i>
                        </button>
                    </div>
                    <p class="confirm-password-error hidden text-danger text-sm">两次输入的密码不一致</p>
                </div>

                <!-- 注册按钮 -->
                <button type="submit" class="w-full bg-primary text-white font-medium py-3 px-4 rounded-lg btn-effect">
                    注册
                </button>
            </form>
        </div>
    </div>

    <!-- 底部信息 -->
    <div class="mt-6 text-center text-neutral-500 text-sm">
        <p>© 2025 基于spark的气息分析系统 </p>
    </div>
</div>

<script>
    // 1. 通用工具函数（适配表单提交）
    const requestForm = (url, formData) =>
        fetch(url, {
            method: 'POST',
            body: formData  // 直接传递FormData（自动适配表单格式）
        })
            .then(res => {
                // 处理后端重定向（登录成功会返回302，需手动跳转）
                if (res.redirected) {
                    window.location.href = res.url;
                    return { code: 200 };
                }
                // 登录失败时，后端返回login页面，这里获取页面内容（用于提取错误信息）
                return res.text().then(html => ({ code: 400, html }));
            })
            .catch(() => ({ code: 500, message: '网络异常' }));

    const showError = (errorEl, message) => {
        errorEl.textContent = message;
        errorEl.classList.remove('hidden');
        errorEl.closest('.space-y-2').querySelector('input').classList.add('border-danger');
    };

    // 2. 元素绑定
    const [loginTab, registerTab] = document.querySelectorAll('[id$="-tab"]');
    const [loginForm, registerForm] = document.querySelectorAll('form');
    const [loginUsername, loginPassword] = document.querySelectorAll('#login-username, #login-password');
    const [registerUsername, registerPassword, confirmPassword] = document.querySelectorAll('#register-username, #register-password, #confirm-password');
    const errorEls = document.querySelectorAll('[class$="-error"]');
    // 登录页错误信息容器（需在HTML中添加一个元素，如：<div id="login-error" class="text-danger hidden"></div>）
    const loginGlobalError = document.getElementById('login-error');

    // 3. 标签切换逻辑（保持不变）
    const switchTab = (showForm, hideForm, activeTab, inactiveTab) => {
        showForm.classList.remove('hidden');
        hideForm.classList.add('hidden');
        activeTab.classList.add('text-primary', 'border-primary');
        inactiveTab.classList.remove('text-primary', 'border-primary');
    };

    loginTab.onclick = () => switchTab(loginForm, registerForm, loginTab, registerTab);
    registerTab.onclick = () => switchTab(registerForm, loginForm, registerTab, loginTab);

    // 4. 密码显示切换（保持不变）
    document.querySelectorAll('.toggle-password').forEach(btn => {
        btn.onclick = () => {
            const input = document.getElementById(btn.dataset.target);
            input.type = input.type === 'password' ? 'text' : 'password';
            btn.querySelector('i').classList.toggle('fa-eye-slash');
        };
    });

    // 5. 表单验证规则（保持不变）
    const validate = {
        username: (val) => val.length < 3 || val.length > 20 ? '用户名需3-20字符' : '',
        password: (val) => val.length < 6 ? '密码需≥6字符' : '',
        confirm: (p1, p2) => p1 !== p2 ? '密码不一致' : ''
    };

    // 6. 登录表单提交（核心修改：适配后端表单接收逻辑）
    loginForm.onsubmit = async (e) => {
        e.preventDefault();
        // 重置错误状态
        errorEls.forEach(el => el.classList.add('hidden'));
        loginGlobalError?.classList.add('hidden');
        document.querySelectorAll('input').forEach(input => input.classList.remove('border-danger'));

        // 前端验证
        const username = loginUsername.value.trim();
        const password = loginPassword.value.trim();
        const uErr = validate.username(username);
        const pErr = validate.password(password);

        if (uErr) return showError(loginUsernameError, uErr);
        if (pErr) return showError(loginPasswordError, pErr);

        // 构造表单数据（适配后端@ModelAttribute接收）
        const formData = new FormData();
        formData.append('username', username);
        formData.append('password', password);

        // 提交表单请求
        const res = await requestForm('/login', formData);

        // 处理登录失败（后端返回错误信息）
        if (res.code === 400) {
            // 从后端返回的login页面中提取error信息（如果后端用模板引擎渲染了error）
            // 简单处理：假设后端在页面中添加了<div id="backend-error">错误信息</div>
            const tempDiv = document.createElement('div');
            tempDiv.innerHTML = res.html;
            const backendError = tempDiv.querySelector('#backend-error')?.textContent;
            if (backendError) {
                loginGlobalError?.classList.remove('hidden');
                loginGlobalError.textContent = backendError;
            } else {
                alert('登录失败：用户名或密码错误');
            }
        } else if (res.code === 500) {
            alert(res.message);
        }
    };

    registerForm.onsubmit = async (e) => {
        e.preventDefault();
        // 1. 重置错误状态（保留原有逻辑）
        errorEls.forEach(el => el.classList.add('hidden'));
        document.querySelectorAll('input').forEach(input => input.classList.remove('border-danger'));

        // 2. 前端验证（示例，根据实际逻辑调整）
        const username = registerUsername.value.trim();
        const password = registerPassword.value.trim();
        const confirm = confirmPassword.value.trim();

        if (username.length < 3 || username.length > 20) {
            showError(registerUsernameError, '用户名需3-20字符');
            return;
        }
        if (password.length < 6) {
            showError(registerPasswordError, '密码需≥6字符');
            return;
        }
        if (password !== confirm) {
            showError(confirmPasswordError, '两次密码不一致');
            return;
        }

        try {
            // 3. 发送 JSON 请求（确保 Content-Type 正确）
            const res = await fetch('/addUser', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json' // 必须设置，否则后端无法解析 JSON
                },
                body: JSON.stringify({ username, password })
            });

            // 4. 解析后端返回的 Result（强制 JSON 解析）
            let data;
            try {
                data = await res.json(); // 解析为 JSON 对象
            } catch (err) {
                alert('服务器返回无效数据，请检查网络或联系管理员');
                console.error('JSON 解析失败，原始响应：', await res.text());
                return;
            }

            // 5. 根据后端的 `ok` 字段判断是否成功（关键修正！）
            if (data.ok) {
                alert('注册成功！即将跳转到登录页');
                // 切换到登录标签（确保 DOM 操作有效）
                loginTab.click();
                // 回显用户名（确保元素存在）
                loginUsername.value = username;
            } else {
                // 注册失败，显示后端返回的 `message`
                alert(`注册失败：${data.message || '未知错误'}`);
            }

        } catch (err) {
            // 网络异常（如断网、跨域）
            alert('网络异常，请重试');
            console.error('网络请求错误：', err);
        }
    };

    // 8. 输入实时清除错误状态（保持不变）
    document.querySelectorAll('input').forEach(input => {
        input.oninput = () => {
            input.classList.remove('border-danger');
            const errorEl = input.closest('.space-y-2').querySelector('.error');
            errorEl && errorEl.classList.add('hidden');
        };
    });

    // 页面加载时检查后端返回的错误信息（如刷新登录页时）
    window.onload = () => {
        // 从URL参数或页面元素获取错误信息（根据后端实际渲染方式调整）
        const urlParams = new URLSearchParams(window.location.search);
        const error = urlParams.get('error');
        if (error && loginGlobalError) {
            loginGlobalError.classList.remove('hidden');
            loginGlobalError.textContent = error;
        }
    };
</script>
</body>
</html>
